package com.tdkj.globalvars;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.widget.Toast;

/**
 * This class echoes a string called from JavaScript.
 */
public class GlobalVars extends CordovaPlugin {
    private String flag = "false";

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("set")) {
            String message = args.getString(0);
            this.set(message, callbackContext);
            return true;
        }
        if (action.equals("get")) {
            this.get(callbackContext);
            return true;
        }

        if (action.equals("toast")) {
            String message = args.getString(0);
            this.toast(message,callbackContext);
            return true;
        }
        return false;
    }

    private void set(String message, CallbackContext callbackContext) {
        if (message != null && message.length() > 0) {
            if (message.equals("true")) {
                flag = "true";
                callbackContext.success(message);
            } else if (message.equals("false")) {
                flag = "false";
                callbackContext.success(message);
            }

        } else {
            callbackContext.error("Expected one non-empty string argument.");
        }
    }

    private void get(CallbackContext callbackContext) {
        if (flag != null && flag.length() > 0) {
            callbackContext.success(flag);
        } else {
            callbackContext.error("Expected one non-empty string argument.");
        }
    }

    private void toast(String message,CallbackContext callbackContext) {
        if (message != null && message.length() > 0) {
            callbackContext.success(message);
            Toast.makeText(cordova.getActivity(), message, Toast.LENGTH_SHORT).show();
        } else {
            callbackContext.error("Expected one non-empty string argument.");
        }
    }
}
